﻿using Google.Protobuf;
using MP_Game.Protos.V1;
using System.Collections.Generic;
using System.Net.Sockets;

namespace MP_Network
{
    public class Session : ServerBase
    {
        public int SessionId { get; set; }
        public Session(Dictionary<CmdId, IContainer> cmdDic, Socket socket)
        {
            _cmdDic = cmdDic;
            _socket = socket;
            SessionMgr.Instance.AddSession(this);
        }
        /// <summary>
        /// 开始监听客户端发来的数据
        /// </summary>
        /// <param name="socket"></param>
        public void ReceiveData(/*Socket socket*/)
        {
            //_socket = socket;
            BeginReceive();
        }
        /// <summary>
        /// BeginReceive收到数据后调用此函数，处理收到的消息
        /// </summary>
        /// <param name="packet"></param>
        protected override void HandleCommand(GamePacket packet)
        {
            LogMsg.Info($"Session::HandleCommand::收到信息{packet}");
            if (packet.SessionId == 0) packet.SessionId = SessionId;
            IContainer container = _cmdDic[packet.CmdId];
            // 没有注册该指令对应的处理器，弹出警告
            if (container == null)
            {
                LogMsg.Warn($"Session::HandleCommand::Command ID: {packet.CmdId} not regist!");
                return;
            }
            container.OnServerCommand(this, packet);
        }

        public void Send(GamePacket packet, int cmdId = -1, ByteString data = null)
        {
            base.SendData(packet, cmdId, data);
        }
        public override void SendData(GamePacket packet, int cmdId = -1, ByteString data = null)
        {
            packet.SessionId = SessionId;
            base.SendData(packet, cmdId, data);
        }

        public override void Disconnect()
        {
            LogMsg.Warn("Session::Disconnect::" + _socket.RemoteEndPoint + "断开了连接!");
            SessionMgr.Instance.RemoveSession(SessionId);
            SessionMgr.Instance.RemoveClient(_clientType);
            base.Disconnect();
        }
    }
}
